package org.jeecg.modules.quartz.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.nc.enums.WSEnum;
import org.jeecg.common.nc.service.NCWebService;
import org.jeecg.common.nc.vo.WSVO;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.nc.entity.NcBdPsnjob;
import org.jeecg.modules.nc.entity.NcOrg;
import org.jeecg.modules.nc.entity.NcPersonnel;
import org.jeecg.modules.nc.service.INcBdPsnjobService;
import org.jeecg.modules.nc.service.INcOrgService;
import org.jeecg.modules.nc.service.INcPersonnelService;
import org.jeecg.modules.quartz.entity.TbJobLog;
import org.jeecg.modules.quartz.service.IQuartzJobService;
import org.jeecg.modules.quartz.service.ITbJobLogService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysDepartServiceImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author: wjb
 * @Date: 2021/12/04/9:33
 * @Description:
 */
public class NCPersonnelSyncJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(NCUserSyncJob.class);

    @Autowired
    IQuartzJobService jobService;

    @Autowired
    SysDepartServiceImpl sysDepartService;

    @Autowired
    private INcPersonnelService ncPersonnelService;

    @Autowired
    private ISysUserService sysUserService;

    @Value("${qixin.ncserver.uri}")
    private String NC_SERVER_URI;

    @Autowired
    private ITbJobLogService tbJobLogService;

    @Autowired
    private INcBdPsnjobService ncBdPsnjobService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    INcOrgService orgService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        // 获取NC组织数据
        try {
            String lastTime = jobService.queryLastTime("ncorgsyncjob");
            String currentTime = DateUtil.now();
            Boolean first = false;
            if (StrUtil.isBlank(lastTime)) {
                lastTime = "2008-01-01 00:00:00";
                first = true; // 表示第一次同步
            }

            WSVO vo = NCWebService.getFromWS(NC_SERVER_URI, WSEnum.ZUZHI,lastTime);
            for (Map<String, Object> map : vo.getContent()) {
                // 同步NC组织
                NcOrg ncOrg = new NcOrg();
                ncOrg.setSid((String) map.get("pk_org"));
                ncOrg.setCode((String) map.get("code"));
                ncOrg.setPkFatherorg((String) map.get("pk_fatherorg"));
                ncOrg.setName((String) map.get("name"));
                ncOrg.setPkGroup((String) map.get("pk_group"));
                ncOrg.setDr(map.get("dr").toString());
                orgService.saveOrUpdate(ncOrg);
                // 添加系统部门
                SysDepart sysDepart = new SysDepart();
                sysDepart.setOrgCategory("1"); // 组织类型 -- 公司
                sysDepart.setCreateBy("admin");
                sysDepart.setUpdateBy("admin");
                sysDepart.setUpdateTime(new Date());
                sysDepart.setId((String) map.get("pk_org"));
                sysDepart.setOrgCode((String) map.get("code"));
                sysDepart.setDepartName((String) map.get("name"));
                sysDepart.setParentId((String) map.get("pk_fatherorg"));
                sysDepart.setDelFlag( map.get("dr").toString());
                sysDepart.setPkGroup((String) map.get("pk_group"));
                sysDepartService.saveOrUpdate(sysDepart);
            }
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC组织同步");
            tbJobLog.setContent("本次新增或更新记录" + vo.getContent().size() + "条");
            tbJobLog.setNum(vo.getContent().size());
            tbJobLogService.save(tbJobLog);
            if(first){
                // 新增一条记录
                jobService.insetLastTime("ncorgsyncjob", currentTime);
            }else{
                //更新最后同步时间
                jobService.updateLastTime("ncorgsyncjob", currentTime);
            }
            logger.info("NC组织同步成功更新：{}条", vo.getContent().size());
        } catch (Exception e) {
            logger.info("NC组织同步出现异常：{}", e.getMessage());
            e.printStackTrace();
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC组织同步");
            tbJobLog.setContent("同步出现异常：" + e.getMessage());
            tbJobLog.setNum(0);
            tbJobLogService.save(tbJobLog);
        }

        // 获取NC部门数据
        try {
            String lastTime = jobService.queryLastTime("ncdeptsyncjob");
            String currentTime = DateUtil.now();
            Boolean first = false;
            if (StrUtil.isBlank(lastTime)) {
                lastTime = "2008-01-01 00:00:00";
                first = true; // 表示第一次同步
            }

            WSVO vo = NCWebService.getFromWS(NC_SERVER_URI, WSEnum.DEPT,lastTime);
            for (Map<String, Object> map : vo.getContent()) {
                String pid = (String) map.get("pk_fatherorg");
                // 添加系统部门
                SysDepart sysDepart = new SysDepart();
                sysDepart.setOrgCategory("2");// 组织类型 -- 部门
                sysDepart.setCreateBy("admin");
                sysDepart.setUpdateBy("admin");
                sysDepart.setUpdateTime(new Date());
                sysDepart.setId((String) map.get("pk_dept"));
                sysDepart.setOrgCode((String) map.get("code"));
                sysDepart.setDepartName((String) map.get("name"));
                if (StrUtil.isBlank(pid)){
                    // 上级部门为空话，把上级部门设成组织
                    sysDepart.setParentId((String) map.get("pk_org"));
                }else{
                    sysDepart.setParentId((String) map.get("pk_fatherorg"));
                }
                sysDepart.setDelFlag( map.get("dr").toString());
                sysDepart.setPkGroup((String) map.get("pk_group"));
                sysDepartService.saveOrUpdate(sysDepart);

 /*               NcOrg ncOrg = new NcOrg();
                ncOrg.setSid((String) map.get("pk_dept"));
                ncOrg.setCode((String) map.get("code"));
                ncOrg.setPkFatherorg(pid);
                ncOrg.setName((String) map.get("name"));
                ncOrg.setPkGroup((String) map.get("pk_group"));
                ncOrg.setDr(map.get("dr").toString());
                orgService.saveOrUpdate(ncOrg);*/

            }
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC组织同步");
            tbJobLog.setContent("本次新增或更新记录" + vo.getContent().size() + "条");
            tbJobLog.setNum(vo.getContent().size());
            tbJobLogService.save(tbJobLog);
            if(first){
                // 新增一条记录
                jobService.insetLastTime("ncdeptsyncjob", currentTime);
            }else{
                //更新最后同步时间
                jobService.updateLastTime("ncdeptsyncjob", currentTime);
            }
            logger.info("NC组织同步成功更新：{}条", vo.getContent().size());
        } catch (Exception e) {
            logger.info("NC组织同步出现异常：{}", e.getMessage());
            e.printStackTrace();
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC组织同步");
            tbJobLog.setContent("同步出现异常：" + e.getMessage());
            tbJobLog.setNum(0);
            tbJobLogService.save(tbJobLog);
        }

        // 获取组织个数
        List<NcOrg> ncOrgs = sysDepartService.querOrgList();

        // 获取NC人员信息
        try {
            String lastTime = jobService.queryLastTime("ncpersonnelsyncjob");
            String currentTime = DateUtil.now();
            Boolean first = false;
            if (StrUtil.isBlank(lastTime)) {
                lastTime = "2008-01-01 00:00:00";
                first = true; // 表示第一次同步
            }

            WSVO vo = new WSVO();
            if (ncOrgs.size() > 0) {
                // 循环组织名称更新人员档案
                for (NcOrg ncOrg : ncOrgs) {
                    WSEnum.PERSONNEL.setMsg(ncOrg.getCode());
                    // WSEnum.PERSONNEL.setMsg("12501");
                    vo = NCWebService.getFromWS(NC_SERVER_URI, WSEnum.PERSONNEL, lastTime);
                    for (Map<String, Object> map : vo.getContent()) {
                        NcPersonnel ncPersonnel = new NcPersonnel();
                        // 主表
                        Map<String, Object> headMap = (Map<String, Object>) map.get("head");
                        ncPersonnel.setCode((String) headMap.get("code")); //人员编码
                        ncPersonnel.setName((String) headMap.get("name")); //姓名
                        ncPersonnel.setPkGroup((String) headMap.get("pk_group")); //所属集团
                        ncPersonnel.setId((String) headMap.get("pk_psndoc")); //人员编码主键
                        ncPersonnel.setPkOrg((String) headMap.get("pk_org")); // 人员组织
                        ncPersonnel.setEnablestate((Integer) headMap.get("enablestate")); //启用状态
                        ncPersonnel.setDr((Integer) headMap.get("dr")); //是否删除
                        ncPersonnel.setMnecode((String) headMap.get("mnecode"));//助记码
                        ncPersonnel.setMobile((String) headMap.get("mobile"));//手机
                        ncPersonnel.setSex((Integer) headMap.get("sex"));//性别
                        ncPersonnel.setNickname((String) headMap.get("nickname")); //昵称
                        ncPersonnel.setUsedname((String) headMap.get("usedname")); //曾用名
                        ncPersonnel.setLevel(3); // 级别 默认设置为 其余人员
                        ncPersonnel.setRank(4); // 职级 默认设置为 一般员工
                        // 子表
                        List<Map<String, Object>> bodyList = new ArrayList<>();
                        bodyList = (List<Map<String, Object>>) map.get("body");
                        if (bodyList.size() > 0) {
                            List<NcBdPsnjob> list = new ArrayList<NcBdPsnjob>();
                            for (Map bodyMap : bodyList) {
                                // 获取目前主职/兼职信息
                                if (bodyMap.get("enddutydate") == null) {
                                    NcBdPsnjob ncBdPsnjob = new NcBdPsnjob();
                                    ncBdPsnjob.setId((String) bodyMap.get("pk_psnjob")); // 任职信息主键
                                    ncBdPsnjob.setIndutydate((String) bodyMap.get("indutydate")); // 任职开始日期
                                    ncBdPsnjob.setEnddutydate((String) bodyMap.get("enddutydate"));// 任职结束日期
                                    ncBdPsnjob.setIsmainjob((String)bodyMap.get("ismainjob"));//    是否主职
                                    ncBdPsnjob.setJobname((String)bodyMap.get("jobname"));  //  职务称谓
                                    ncBdPsnjob.setPkDept((String)bodyMap.get("pk_dept"));   //  所在部门
                                    ncBdPsnjob.setPkGroup((String)bodyMap.get("pk_group")); //  所在集团
                                    ncBdPsnjob.setPkJob((String)bodyMap.get("pk_job")); //  职务
                                    ncBdPsnjob.setPkOrg((String)bodyMap.get("pk_org")); //  组织
                                    ncBdPsnjob.setPkPost((String)bodyMap.get("pk_post"));  //  岗位
                                    ncBdPsnjob.setPkPsncl((String)bodyMap.get("pk_psncl"));//  人员类别
                                    ncBdPsnjob.setPsncode((String)bodyMap.get("psncode")); //   员工编码
                                    ncBdPsnjob.setDr((Integer) bodyMap.get("dr"));// 是否删除
                                    ncBdPsnjob.setPkPsndoc((String) bodyMap.get("pk_psndoc"));// 人员编码
                                    // 判断该条任职信息是否是主职信息，是的话将部门数据添加到对应的人员部门信息中
                                    if("Y".equals(ncBdPsnjob.getIsmainjob())){
                                        ncPersonnel.setPkDept((String)bodyMap.get("pk_dept"));
                                    }
                                    list.add(ncBdPsnjob);

                                }
                            }
                            // 删除子表数据
                            QueryWrapper<NcBdPsnjob> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("pk_psndoc",headMap.get("pk_psndoc"));
                            ncBdPsnjobService.remove(queryWrapper);
                            // 保存子表数据
                            ncBdPsnjobService.saveBatch(list);
                        }
                        ncPersonnelService.saveOrUpdate(ncPersonnel);
                    }

                    TbJobLog tbJobLog = new TbJobLog();
                    tbJobLog.setName(ncOrg.getName() + "NC人员档案同步");
                    tbJobLog.setContent(ncOrg.getName() + "本次新增或更新记录" + vo.getContent().size() + "条");
                    tbJobLog.setNum(vo.getContent().size());
                    tbJobLogService.save(tbJobLog);
                }
                // 更新用户表字段 org_code 的值
                sysUserService.updateUserOrgCode();
                //更新人员档案的组织名称以及部门名称
                ncPersonnelService.updatePsNOrgAndDept();

                if (first) {
                    // 新增一条记录
                    jobService.insetLastTime("ncpersonnelsyncjob", currentTime);
                } else {
                    //更新最后同步时间
                    jobService.updateLastTime("ncpersonnelsyncjob", currentTime);
                }
                logger.info("NC人员档案同步成功更新：{}条", vo.getContent().size());
            }
        } catch (Exception e) {
            logger.info("NC人员档案同步出现异常：{}", e.getMessage());
            e.printStackTrace();
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC人员档案同步");
            tbJobLog.setContent("同步出现异常：" + e.getMessage());
            tbJobLog.setNum(0);
            tbJobLogService.save(tbJobLog);
        }

        // 获取NC用户信息
        try {
            String lastTime = jobService.queryLastTime("ncusersyncjob");
            String currentTime = DateUtil.now();
            Boolean first = false;
            if (StrUtil.isBlank(lastTime)) {
                lastTime = "2008-01-01 00:00:00";
                first = true; // 表示第一次同步
            }

            WSVO vo = new WSVO();
            if (ncOrgs.size() > 0) {
                // 循环组织名称更新人员档案
                for (NcOrg ncOrg : ncOrgs) {
                    WSEnum.USER.setMsg(ncOrg.getCode());
                    vo = NCWebService.getFromWS(NC_SERVER_URI, WSEnum.USER,lastTime);
                    for (Map<String, Object> map : vo.getContent()) {
                        SysUser user =  new SysUser();
                        String pkPsndoc = (String) map.get("pk_psndoc"); // 人员主键
                        String islocked = (String) map.get("islocked");
                        String enablestate = map.get("enablestate").toString();
                        user.setId((String) map.get("cuserid"));
                        user.setUsername((String) map.get("user_code")); // 登陆账号
                        user.setRealname((String)map.get("user_name"));
                        user.setPkPsndoc((String)map.get("pk_psndoc")); // 人员档案主键

                        // update-begin-by wujinbiao 2022/3/28 11:27 for 添加用户电话信息、添加默认角色信息
                        if(StringUtils.isNotBlank((String)map.get("pk_psndoc"))){
                            NcPersonnel ncPersonnel = ncPersonnelService.queryById((String) map.get("pk_psndoc"));
                            if (ncPersonnel != null){
                                user.setPhone(ncPersonnel.getMobile());
                            }
                        }
                        SysUserRole sysUserRole = new SysUserRole(user.getId(),"1506464874367115265");
                        QueryWrapper<SysUserRole> queryWrapper2 = new QueryWrapper<SysUserRole>();
                        queryWrapper2.eq("role_id", "1506464874367115265").eq("user_id",user.getId());
                        SysUserRole one = sysUserRoleService.getOne(queryWrapper2);
                        if(one==null){
                            sysUserRoleService.save(sysUserRole);
                        }
                        // update-end-by wujinbiao 2022/3/28 11:27 for 添加默认角色信息、添加默认角色信息
                        user.setStatus(1); // 状态(1：正常  2：冻结 ）
                        if(!"N".equals(islocked) || !"2".equals(enablestate)){
                            user.setStatus(2);
                        }
                        if(StrUtil.isNotBlank(pkPsndoc)){
                            // 获取用户对应人员的部门信息
                            NcPersonnel ncPersonnel = ncPersonnelService.queryById(pkPsndoc);
                            if (ncPersonnel != null){
                                user.setOrgCode(ncPersonnel.getPkOrg());
                                // 在表sys_user_depart 添加用户与部门的对应关系
                                SysUserDepart sysUserDepart2 = sysUserDepartService.queryByUserid(user.getId());
                                if(sysUserDepart2 == null){
                                    // 数据不存在
                                    SysUserDepart sysUserDepart = new SysUserDepart(user.getId(),ncPersonnel.getPkDept());
                                    sysUserDepartService.save(sysUserDepart);
                                }else{
                                    // 数据存在 那就更新一下
                                    sysUserDepart2.setUserId(user.getId());
                                    sysUserDepart2.setDepId(ncPersonnel.getPkDept());
                                    sysUserDepartService.updateById(sysUserDepart2);
                                }
                            }
                        }
                        QueryWrapper queryWrapper = new QueryWrapper();
                        queryWrapper.eq("id",(String) map.get("cuserid"));
                        Integer count = sysUserService.count(queryWrapper);
                        if(count == 0){
                            String salt = oConvertUtils.randomGen(8);
                            user.setSalt(salt);
                            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), "1qaz@wsx", salt); // 设置默认密码
                            user.setPassword(passwordEncode);
                        }

                        //user.setOrgCode((String) map.get("pk_org"));
                        user.setOrigin("NC6.5");
                        user.setDelFlag((Integer) map.get("dr"));
                        user.setUserType(1);
                        sysUserService.saveOrUpdate(user);
                    }
                    TbJobLog tbJobLog = new TbJobLog();
                    tbJobLog.setName(ncOrg.getName() + "NC用户同步");
                    tbJobLog.setContent(ncOrg.getName() + "本次新增或更新记录" + vo.getContent().size() + "条");
                    tbJobLog.setNum(vo.getContent().size());
                    tbJobLogService.save(tbJobLog);
                }
                if(first){
                    // 新增一条记录
                    jobService.insetLastTime("ncusersyncjob", currentTime);
                }else{
                    //更新最后同步时间
                    jobService.updateLastTime("ncusersyncjob", currentTime);
                }
                logger.info("NC用户同步成功更新：{}条", vo.getContent().size());
            }

        } catch (Exception e) {
            logger.info("NC用户同步出现异常：{}", e.getMessage());
            e.printStackTrace();
            TbJobLog tbJobLog = new TbJobLog();
            tbJobLog.setName("NC用户同步");
            tbJobLog.setContent("同步出现异常：" + e.getMessage());
            tbJobLog.setNum(0);
            tbJobLogService.save(tbJobLog);
        }


    }
}
